
var ws = new WebSocket("ws://"+window.location.host+"/viewer");

function startWebSocket()
{

  //$.data(document.body, "socket",ws);

  ws.onopen = function() {

    // Send hello here is the client
    //ws.send("here is the client");
  };

  ws.onmessage = function (evt) {
    //console.log(evt);
    var obj = $.parseJSON(evt.data);
    //console.log(obj);

    // the number of lines, its important for the x Position of the tile
    var numberOfLines = 13;
    var numberOfVisibleLines = 9;

    if(obj.lines != undefined)
    {
      for(var i=0; i<obj.lines.length; i++)
      {
        var lineObj = obj.lines[i];
        var lineId = lineObj.id;



        if(lineObj.content == "linkskurve" )
        {

          var currentLine = Math.floor($.data(document.body, "totalDistance") / 100);
          var posFactor = lineId - currentLine;
          Crafty.e("2D, Canvas, CurveObjectLeft, Image, LineObject, curve").image("pic/linkskurvelang.png").attr({x:-1500, y: 800 - 1200 - (posFactor * 100) + ($.data(document.body, "totalDistance") % 100), z: 2});
          $.data(document.body,"curveModeLeft",true);

        }else if(lineObj.content == "rechtskurve")
        {
          var currentLine = Math.floor($.data(document.body, "totalDistance") / 100);
          var posFactor = lineId - currentLine;
          Crafty.e("2D, Canvas, CurveObjectRight, Image, LineObject, curve").image("pic/rechtskurvelang.png").attr({x:-200, y: 800 - 1200 - (posFactor * 100) + ($.data(document.body, "totalDistance") % 100), z: 2});
          $.data(document.body,"curveModeRight",true);
        }
        else{

          //console.log(lineId);
          //console.log(lineObj.content);


          for(var j=0; j<lineObj.content.length; j++)
          {

            var currentLine = Math.floor($.data(document.body, "totalDistance") / 100);
            var posFactor = lineId - currentLine;

            // grass
            //Crafty.e("2D, Canvas, gras100, LineObject").attr({x:(((numberOfVisibleLines - numberOfLines) / 2 )+ j) * 100, y: 800 - (posFactor * 100) + ($.data(document.body, "totalDistance") % 100), z: 2});
            if(lineObj.content[j] == null)
            {
              continue;
            }

            switch(lineObj.content[j])
            {
              case "baum1":
                Crafty.e("2D, Canvas, baum1, LineObject, Line"+currentLine + ", Pos"+j).attr({x:(((numberOfVisibleLines - numberOfLines) / 2 )+ j) * 100, y: 800 - (posFactor * 100) + ($.data(document.body, "totalDistance") % 100), z: 40});
                Crafty.e("2D, Canvas, baum2, LineObject, Line"+currentLine + ", Pos"+j).attr({x:(((numberOfVisibleLines - numberOfLines) / 2 )+ j) * 100, y: 800 - ((posFactor-1) * 100) + ($.data(document.body, "totalDistance") % 100), z: 30});
                break;
              case "Baumstamm2":
                Crafty.e("2D, Canvas, "+lineObj.content[j]+", LineObject, ToDestroy"+lineId).attr({x:(((numberOfVisibleLines - numberOfLines) / 2 )+ j) * 100, y: 800 - (posFactor * 100) + ($.data(document.body, "totalDistance") % 100), z: 40});
                break;
              default:
                Crafty.e("2D, Canvas, "+lineObj.content[j]+", LineObject, Line"+currentLine + ", Pos"+j).attr({x:(((numberOfVisibleLines - numberOfLines) / 2 )+ j) * 100, y: 800 - (posFactor * 100) + ($.data(document.body, "totalDistance") % 100), z: 40});
            }


          }

        }
      }


    }


    if(obj.input_count != undefined){
      //console.log(obj.input_count);
      $("#devices").html(obj.input_count);
    }

    if(obj.score != undefined){
      $("#Score").html(obj.score);
    }

    if(obj.message != undefined)
    {
      $("#Score").html(obj.score);
      console.log(obj.message);

      $("#messages").stop();
      $("#messages").show().css("opacity","1").html(obj.message);
      var duration = 1600;
      if(obj.duration != undefined && obj.duration > 0)
      {
        duration = obj.duration;
      }
      $("#messages").animate({opacity: 0},duration);
    }

    if(obj.train_speed != undefined)
    {
      $.data(document.body,"trainSpeed", obj.train_speed);
    }

    if(obj.coal != undefined){
      $.data(document.body,"kesselMode",obj.coal);
    }

    if(obj.inputs != undefined)
    {
      for(var i=0; i<obj.inputs.length; i++)
      {
        $("#user"+i).html(obj.inputs[i].username);
        $("#smartphone"+i).find("img").hide();
        if(!obj.inputs[i].upside_down)
        {
          $("#smartphone"+i).find(".front").show();
        }
        else
        {
          $("#smartphone"+i).find(".back").show();
        }
        if(obj.inputs[i].position != undefined)
        {
          switch(obj.inputs[i].position)
          {
            case("shovel"):
              $("#smartphone"+i).find("span").html("shovel");
              break;
            case("shake"):
              $("#smartphone"+i).find("span").html("shake");
              break;
            case("swipe"):
              $("#smartphone"+i).find("span").html("swipe");
              break;
            case("image_quiz"):
              $("#smartphone"+i).find("span").html("image_quiz");
              break;
          }
        }
        else
        {
          $("#smartphone"+i).find("span").html("");
        }


      }
    }

    if(obj.gameover == true)
    {
      var explosion = Crafty.e("2D, DOM, Image").attr({x: 200,y:300,w: 500,h: 500}).image("pic/explosion.png");
    }

    if(obj.remove_middle != undefined && obj.remove_middle > 0)
    {
      var middleObject = Crafty("ToDestroy"+obj.remove_middle);
      console.log("TO KILL: ToDestroy"+obj.remove_middle);
      console.log(middleObject);
      middleObject.destroy();
    }

    if(obj.next_direction != undefined && $.data(document.body,"nextDirectionLock") != true)
    {
      $.data(document.body,"nextDirection",obj.next_direction);
    }

    if(obj.reload == true)
    {
      location.reload();
    }

  }

};

ws.onclose = function()
{
  //ws = new WebSocket("ws://localhost:8000/viewer");
};


